package com.example.itcacp.repository.mybatis;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.itcacp.entity.Category;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface CategoryMapper extends BaseMapper<Category> {

    @SelectProvider(type = CateSqlProvider.class, method = "selectCateAll")
    @Results({
            @Result(property = "categoryId", column = "category_id"),
            @Result(property = "parentId", column = "parent_id"),
            @Result(property = "categoryName", column = "category_name"),
            @Result(property = "created_at", column = "created_at"),
            @Result(property = "updated_at", column = "updated_at"),
    })
    List<Category> selectCateAll(String categoryName);

    class CateSqlProvider {
        public String selectCateAll(String categoryName) {
            return new SQL() {{
                SELECT ( "*" );
                FROM ( "tc_category" );
                boolean isWHERE = false; // categoryName为空时不添加WHERE语句
                if (categoryName != null && !categoryName.isEmpty ()) {
                    WHERE ( "category_name LIKE CONCAT('%', #{categoryName}, '%')" );
                    isWHERE = true;
                }
            }}.toString ();
        }
    }
}
